package cn.tedu.straw.portal.service.impl;

import cn.tedu.straw.portal.dto.PostCommentDTO;
import cn.tedu.straw.portal.ex.AnswerNotFoundException;
import cn.tedu.straw.portal.ex.InsertException;
import cn.tedu.straw.portal.mapper.AnswerMapper;
import cn.tedu.straw.portal.mapper.CommentMapper;
import cn.tedu.straw.portal.model.Answer;
import cn.tedu.straw.portal.model.Comment;
import cn.tedu.straw.portal.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-10-15
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    AnswerMapper answerMapper;
    @Autowired
    CommentMapper commentMapper;

    @Override
    public void post(PostCommentDTO postCommentDTO, Integer userId, String userNickName) {
        Integer answerId=postCommentDTO.getAnswerId();
        //从参数postCommentDTO中获取answerId
        Answer answer=answerMapper.findById(answerId);
        //判断查询结果是否为null
        if(answer==null){
            throw new AnswerNotFoundException("发表评论失败!答案数据不存在!");
        }

        //创建当前时间对象
        LocalDateTime now=LocalDateTime.now();
        //创建Comment对象
        Comment comment=new Comment();
        //向Comment中添加数据
        comment.setContent(postCommentDTO.getContent());
        comment.setUserId(userId);
        comment.setUserNickName(userNickName);
        comment.setAnswerId(answerId);
        comment.setGmtCreate(now);
        comment.setGmtModified(now);

        int rows=commentMapper.insert(comment);
        if(rows!=1){
            throw new InsertException("发表评论失败!服务器忙,请稍后再次尝试!");
        }
    }
}
